﻿/*************************************************************************************

- CLR版本：        4.0.30319.42000
- 类 名 称：       MesHelperSharp
- 机器名称：       YTE
- 命名空间：       LD.Tool.MES.sharp
- 文 件 名：       MesHelperSharp
- 创建时间：       2022/7/31 19:45:25
- 作    者：       YTE
- 说   明：
- 修改时间：
- 修 改 人：
  *************************************************************************************/

using LD.Host;
using LD.Host.项目;
using LD.PLC;
using System;
using System.Collections.Generic;
using System.Linq;

namespace LD.Tool
{
    [Tool(Text = "螺丝机", FrmParam = "ToolScrewFrm", ToolType = ToolEnum.项目)]

    public class ToolScrew : BaseTool
    {
        private ScrewHelper screwHelper;
        private List<short> CHN1;
        private List<short> CHN2;
        private List<TB_ScrewDetailData> _screwDetailData;
        private TB_Tool _tool;
        private ToolScrewParame _param;
        private short[] _screwData;
        private bool _screwLast;
        private TB_ScrewData screwMainData;
        public ToolScrew()
        {
            CHN1 = new List<short>();
            CHN2 = new List<short>();
            _screwDetailData = new List<TB_ScrewDetailData>();
            screwMainData = new TB_ScrewData();
        }
        public override OpResult Execute(TB_Tool model)
        {
            _tool = model;
            try
            {
                stopwatch.Start();
                if (model.Param != null)
                {
                    _param = Newtonsoft.Json.JsonConvert.DeserializeObject<ToolScrewParame>(model.Param);
                    if (_param != null)
                    {
                        string barcode = string.Empty;
                        var opBarcode = PLCFactory.Instance.ReadString(_param.AdrBarcode, 50);
                        var opNum = PLCFactory.Instance.ReadInt16(_param.AdrScrewNum);
                        var opLast = PLCFactory.Instance.ReadInt16(_param.AdrScrewLast);
                        if (opBarcode.IsSuccess && opNum.IsSuccess && opLast.IsSuccess)
                        {
                            barcode = opBarcode.Content.Trim().Replace("\0", "").Replace(" ", "");
                            if (string.IsNullOrEmpty(barcode))
                                barcode = "Test";

                            _screwLast = opLast.Content == 1;
                            screwMainData.Num = opNum.Content;
                            screwMainData.SN = barcode;

                            //获取8个螺丝的groupId
                            if (screwMainData.Num == 1)
                                ScrewDB.SlotIds[_param.Slot] = ScrewDB.NewId;
                            screwMainData.GroupId = string.IsNullOrEmpty(ScrewDB.SlotIds[_param.Slot]) ? ScrewDB.NewId : ScrewDB.SlotIds[_param.Slot];

                            screwHelper = new ScrewHelper(CommunicateFactory.Instance.ModbusRtus[_param.MobsRtu].Ins);
                            screwHelper.Chn1DataEvent += ScrewHelper_Chn1DataEvent;
                            screwHelper.Chn2DataEvent += ScrewHelper_Chn2DataEvent;
                            screwHelper.CompletedDataEvent += ScrewHelper_CompletedDataEvent;
                            screwHelper.CompletedEvent += ScrewHelper_CompletedEvent;
                            screwHelper.ErrorEvent += ScrewHelper_ErrorEvent;
                            screwHelper.StartedEvent += ScrewHelper_StartedEvent;
                            screwHelper.Start().Wait();
                        }
                    }
                }

                if (!isSuccess)
                    EchoPLC(model.EchoPLC);
            }
            catch (Exception ex)
            {
                Log(model, ex.Message, LogLevel.严重);
            }
            finally
            {
                stopwatch.Stop();
            }
            return new OpResult() { IsSuccess = isSuccess, Message = message, ExecuteTime = stopwatch.ElapsedMilliseconds, Append = _screwDetailData };
        }
        private void WriteDB()
        {
            screwMainData.Slot = "Slot" + _param.Slot;                    //穴位
            screwMainData.TaskId = _screwData[0];                         //程序号
            screwMainData.Rounds = Math.Round(_screwData[1] / 100.0, 2);  //圈数
            screwMainData.Torque = (_screwData[3] * 0.01);                //扭力
            screwMainData.SpeedFeedback = CHN1.Max();                     //速度
            screwMainData.TimeConsuming = _screwData[4];                  //结束时间
            screwMainData.IsCsv = false;

            string errorMsg = string.Empty;
            bool state = screwHelper.getResult(_screwData[5], _screwData[13], out errorMsg);
            screwMainData.Result_State = state ? "OK" : "NG";//结果状态
            screwMainData.Alarm_State = state ? "NO" : errorMsg;//报警状态

            short val = state ? (short)1 : (short)2;
            PLCFactory.Instance.Write(_param.AdrResult, val);
            Log(_tool, $"{screwMainData.SN}:第{screwMainData.Num}颗打钉结束", LogLevel.一般);

            ScrewDB.MainTable(_screwData[9], screwMainData, CHN1, CHN2, _screwLast);

            PubSub.Hub.Default.PublishAsync(new ScrewHandle()
            {
                Barcode = screwMainData.SN,
                Message = state ? "OK" : errorMsg,
                Num = screwMainData.Num,
                KazamState = state ? KazamState.Testing : KazamState.Error,
                Slot = _param.Slot,
            });

        }
        private void ScrewHelper_StartedEvent()
        {
            short val = 2;
            PLCFactory.Instance.Write(_param.AdrStarted, val);
            Log(_tool, $"{screwMainData.SN}:第{screwMainData.Num}颗打钉启动", LogLevel.一般);
        }

        private void ScrewHelper_ErrorEvent(string log)
        {
            Log(_tool, log, LogLevel.警告);
            PubSub.Hub.Default.PublishAsync(new ScrewHandle()
            {
                Message = log,
                Num = screwMainData.Num,
                KazamState = KazamState.Error,
                Slot = _param.Slot
            });
        }

        private void ScrewHelper_CompletedEvent()
        {
            short val = 1;
            PLCFactory.Instance.Write(_param.AdrScrewComplete, val);
            WriteDB();
        }

        private void ScrewHelper_CompletedDataEvent(short[] data)
        {
            _screwData = data;
        }

        private void ScrewHelper_Chn2DataEvent(short[] data)
        {
            CHN2.AddRange(data);
        }
        private void ScrewHelper_Chn1DataEvent(short[] data)
        {
            CHN1.AddRange(data);
        }
    }
}
